<template>
  <div class="domain-group-table-list flex-1 flex flex-col overflow-auto">
    <div class="filter my-4 flex items-center">
      <div class="filter-left flex gap-x-4">
        <el-button type="primary" @click="openEditGroupDialog()">
          新建分组
        </el-button>
        <el-button
          plain
          :disabled="!selectedRows?.length"
          class="ml-0"
          type="primary"
          @click="handleBatchDelete(selectedRows || [])"
        >
          批量删除
        </el-button>
        <el-input
          v-model="queryParams.name"
          class="w-[240px] search-input"
          placeholder="请输入组名"
          clearable
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch()" />
          </template>
        </el-input>
        <basic-refresh-btn :loading="loading" @click="getList()" />
        <!-- <el-autocomplete
          ref="groupRef"
          clearable
          v-model="queryParams.name"
          class="w-[240px]"
          placeholder="请输入组名"
          :fetch-suggestions="groupFetch"
          @change="handleSearch"
          @select="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-autocomplete> -->
      </div>
    </div>

    <div class="flex-1 overflow-auto">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        class="basic-table"
        height="100%"
        :tooltip-options="{ popperClass: 'basic-tooltip' }"
        @selection-change="handleTableSelectionChange"
      >
        <template #empty><TableEmpty /></template>
        <el-table-column type="selection" width="60"></el-table-column>
        <el-table-column label="分组名称" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-format-table-cell="row.name"></span>
          </template>
        </el-table-column>
        <el-table-column label="已关联域名数" min-width="150">
          <template #default="{ row }">
            <el-link
              type="primary"
              :underline="false"
              @click="toDomainListPage(row.id)"
            >
              <span v-format-table-cell="row.domain_num"></span>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="200">
          <template #default="{ row }">
            <basic-edit-table-remark
              :content="row.remark"
              :submit="value => handleEditRemark(row, value)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110">
          <template #default="{ row }">
            <div class="flex gap-x-4">
              <el-link
                type="primary"
                :underline="false"
                @click="openEditGroupDialog(row)"
              >
                编辑
              </el-link>
              <el-link
                type="danger"
                :underline="false"
                @click="handleDelete(row)"
              >
                删除
              </el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="py-4 pl-[24px]">
      <basic-pagination
        ref="paginationRef"
        :table-ref="tableRef"
        :batch-button-props="{
          disabled: !selectedRows || selectedRows.length === 0
        }"
        :pagination="pagination"
        @change="getList"
      ></basic-pagination>
    </div>
  </div>

  <edit-group-dialog
    v-model:visible="editGroup.visible"
    v-model:loading="editGroup.loading"
    :record="editGroup.record"
    @reload="getList"
  ></edit-group-dialog>
</template>

<script setup lang="ts">
/**
 * 此组件需要根据 props 的 user 来决定操作的是所有分组，还是用户分组
 */
import { Search } from '@element-plus/icons-vue'
import type { TableInstance } from 'element-plus'
import type { Ref } from 'vue'

import type { DomainGroupModel } from '@/apis/model/domain'
import type { UserModel } from '@/apis/model/user'
import useTableSelection from '@/hooks/useTableSelection'

import EditGroupDialog from './dialogs/EditGroupDialog.vue'
import useGroupAction from './hooks/useGroupAction'
import useTableList from './hooks/useTableList'
import type { IQuery } from './types'

interface IProps {
  user?: UserModel
}

const router = useRouter()

const props = defineProps<IProps>()

const tableRef = ref<TableInstance>()
const paginationRef = ref()

// const groupRef = ref()
// const fn = props.user ? userDomainGroupListApi : domainGroupListApi
// const { fetchFn: groupFetch } = useSearch('name', fn, {
//   domRef: groupRef
// })

/**
 * 查询参数
 */
const queryParams = reactive<IQuery>({
  name: '',
  remark: ''
})

/**
 * 列表数据
 */
const { tableData, getList, loading, pagination } = useTableList(
  queryParams,
  props.user
)

const handleSearch = () => {
  pagination.page = 1
  pagination.offset = 0
  getList()
}

onMounted(() => {
  if (props.user) {
    queryParams.user_id = props.user.id
  }
  getList()
})

const { selectedRows, handleTableSelectionChange } = useTableSelection(
  tableData,
  paginationRef
)

/**
 * 列表操作
 */
const { handleDelete, handleBatchDelete, handleEditRemark } = useGroupAction({
  refreshFn: getList,
  user: props.user,
  tableData,
  pagination,
  selectedRows: selectedRows as Ref<any[]>
})

/**
 * 新建/编辑分组
 */
const editGroup = reactive<CommonDialog>({
  visible: false,
  loading: false,
  record: null
})

const openEditGroupDialog = (row?: DomainGroupModel) => {
  editGroup.record = row
  editGroup.visible = true
}

/**
 * 跳转域名列表页面
 */
const toDomainListPage = (groupId: string) => {
  if (props.user?.id) {
    router.replace({
      name: 'ManagerUserDomain',
      params: { id: props.user.id },
      query: {
        groupId: groupId
      }
    })
  } else {
    router.push({ name: 'DomainList', query: { groupId } })
  }
}

/**
 * 依赖注入
 */
provide('user', toRef(props, 'user'))
</script>

<style scoped lang="scss"></style>
